package dao;



import util.ConfingManager;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * Created by Administrator on 2019/3/19.
 */
public class BaseDao {
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;

//    private String driver= ConfingManager.getInstance().getValues("driver");
//    private String url=ConfingManager.getInstance().getValues("url");
//    private String name=ConfingManager.getInstance().getValues("name");
//    private String pass=ConfingManager.getInstance().getValues("pass");
    /**
     * 获取连接
     *
     * @return
     */
    public boolean getConn(){
        boolean flag=false;
        try {
            Context ctx=new InitialContext();
            DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/kgcnews");
            conn=ds.getConnection();
            flag=true;
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
    public boolean getConnection() {
        boolean flag = false;
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
             String url = "jdbc:mysql://localhost:3306/kgcnews";
            conn = DriverManager.getConnection(url,"root", "123456");
            flag = true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 查询
     */
    public ResultSet excuteSelect(String sql, Object[] params) {
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 更新
     */
    public int excuteUpdateRows(String sql, Object[] params) {
        int num = 0;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            num = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 关闭
     */
    public void closeConnection() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
